package com.sadam.ui4.FragmentHomePage;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.sadam.ui4.ActivityLogin;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.Data.Video;
import com.sadam.ui4.FragmentSearchPage.FragmentSearchPage;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.MyVideoView;
import com.sadam.ui4.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


/**
 * 主页 Fragment 类，用于展示短视频列表（类似抖音竖屏滑动播放）
 * 支持滑动切换视频、音量/亮度调节手势等交互功能
 */
public class FragmentHomePage extends Fragment {
    // 定义传递参数的键名常量
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private VideoView videoView;

    // 接收传入的参数
    private String mParam1;
    private String mParam2;
    // 与 Activity 通信的回调接口

    private OnFragmentInteractionListener mListener;
    private Context context;
    // 视频宽高相关变量
    private int mVideoWidth, mVideoHeight, showVideoHeight;
    private float scale; // 视频宽高比
    // 自定义视频播放控件
    private MyVideoView myVideoView;
    // 手势操作相关变量 (触摸起始坐标、有效滑动范围、 屏幕宽高（像素）)
    private int startY, startX, touchRang, screenWidth, screenHeight;
    private String TAG = "SADAM<<<";// 日志标签
    private VideoAdapter videoAdapter;
    private MySqLiteOpenHelper dbHelper;
    private RecyclerView recyclerView;
    private Button searchButton;
    private boolean shouldUseRecommendation = true; // 控制是否使用推荐算法

    public FragmentHomePage() {
        // Required empty public constructor
    }

    /**
     * 工厂方法：创建该 Fragment 实例并传入参数
     * @param param1 参数1
     * @param param2 参数2
     * @return 新的 Fragment 实例
     */
    public static FragmentHomePage newInstance(String param1, String param2) {
        FragmentHomePage fragment = new FragmentHomePage();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    /**
     * Fragment 创建时调用，用于初始化参数
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }
    /**
     * 创建视图：加载布局、初始化控件、设置适配器和手势
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 加载 fragment_fragment_home_page 布局文件
        View view = inflater.inflate(R.layout.fragment_fragment_home_page, container, false);
        // 找到 RecyclerView 控件
        recyclerView = view.findViewById(R.id.recyclerview_video);
        // 设置线性布局管理器（垂直方向）
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        // 创建数据库实例
        dbHelper = new MySqLiteOpenHelper(getContext(), MySqLiteOpenHelper.DATABASE_NAME, null, MySqLiteOpenHelper.DATABASE_VERSION);
        // 插入测试数据（仅一次）
        dbHelper.insertTestUsers();
        dbHelper.insertTestVideos();
        dbHelper.insertTestLikes();

        // 从数据库获取所有视频
        ArrayList<Video> videos = new ArrayList<>();
        try {
            videos = dbHelper.getAllVideos();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "加载视频失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        // 创建适配器，传入主 Activity 上下文
//        VideoAdapter videoAdapter = new VideoAdapter((MainActivity) getActivity());
        videoAdapter = new VideoAdapter((MainActivity) getActivity(), dbHelper);
        // 填充视频数据
//        videoAdapter.setVideos(videos);
        // 设置适配器
        recyclerView.setAdapter(videoAdapter);

        // 首次加载数据
        refreshVideoData();


        // 使用 PagerSnapHelper 实现“一页一视频”的滑动效果
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(recyclerView);

        // 获取屏幕尺寸信息
        WindowManager wm = (WindowManager) getActivity()
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);
        screenWidth = displayMetrics.widthPixels;
        screenHeight = displayMetrics.heightPixels;
        float density = displayMetrics.density;  //屏幕密度
        int densityDpi = displayMetrics.densityDpi;//屏幕密度Dpi
        int screenWidth_dp = (int) (screenWidth / density); // 转换为 dp 单位
        int screenHeight_dp = (int) (screenHeight / density);
        // 输出屏幕尺寸日志
        Log.e("SCREEN_WIDTH_pixel", screenWidth + "|" + screenHeight);
        Log.e("SCREEN_WIDTH_dp", screenWidth_dp + "|" + screenHeight_dp);
        
        // 创建手势检测器，用于监听单击、长按、滑动等手势
        final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.OnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                Toast.makeText(getContext(), "onDown", Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public void onShowPress(MotionEvent e) {
                Toast.makeText(getContext(), "onShowPress", Toast.LENGTH_SHORT).show();
            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                Toast.makeText(getContext(), "onSingleTapUp", Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                Toast.makeText(getContext(), "onScroll", Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                Toast.makeText(getContext(), "onLongPress", Toast.LENGTH_SHORT).show();
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                Toast.makeText(getContext(), "onFling", Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        // 找到搜索按钮并设置点击事件
        Button searchButton = view.findViewById(R.id.button2);
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openSearchPage();
            }
        });
        
        return view;
    }
    /**
     * 打开搜索页面（全屏对话框）
     */
    private void openSearchPage() {
        FragmentSearchPage searchDialog = new FragmentSearchPage();
        searchDialog.show(getParentFragmentManager(), "search_dialog");

        Log.d("FragmentHomePage", "🔍 打开搜索页面");
    }

    public void refresh() {
        Log.d("FragmentHomePage", "📢 收到刷新请求");
        refreshVideoData();
    }
    //重新刷新 竖屏显示的大小  树屏显示以宽度为准
    public void refreshPortraitScreen(int height) {
        if (height == 0) {
            height = showVideoHeight;
        }
        if (mVideoHeight > 0 && mVideoWidth > 0) {
            //FixMe 拉伸比例
            // 根据原始视频宽高比计算新宽度
            mVideoWidth = (int) (height * scale);//FixMe 设置surfaceview画布大小
//            mVideoHeight = (int) (mVideoWidth / scale);
            // 调整 SurfaceHolder 大小
            myVideoView.getHolder().setFixedSize(mVideoWidth, height);
            Log.i("竖屏时视频的宽高==", "宽=" + mVideoWidth + "，高=" + mVideoHeight);
            //FixMe 重绘VideoView大小，这个方法是在重写VideoView时对外抛出方法
//            myVideoView.setMeasure(mVideoWidth, height);
            //FixMe 请求调整
            // 请求重新布局
            myVideoView.requestLayout();
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    /**
     * 当 Fragment 被附加到 Activity 时调用
     * 检查 Activity 是否实现了通信接口
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * 通信接口：用于 Fragment 与 Activity 之间的交互
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    // FragmentHomePage.java
    @Override
    public void onPause() {
        super.onPause();
        if (isHidden() || !isResumed()) {
            pauseAllVideos();
        }
    }

    /**
     * 遍历 RecyclerView，暂停所有 ViewHolder 中的视频
     */
    public void pauseAllVideos() {
        if (recyclerView == null || videoAdapter == null) return;

        // 遍历当前可见的 ViewHolder
        for (int i = 0; i < recyclerView.getChildCount(); i++) {
            View child = recyclerView.getChildAt(i);
            VideoViewHolder holder = (VideoViewHolder) recyclerView.getChildViewHolder(child);
            holder.pause(); // 调用 ViewHolder 的 pause 方法
        }

        Log.d("FragmentHomePage", "⏸️ 所有视频已暂停");
    }
    // FragmentHomePage.java

    public void resumeVideoIfVisible() {
        Log.d("FragmentHomePage", "▶️ 尝试恢复视频播放");

        if (recyclerView == null || videoAdapter == null) return;

        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        if (layoutManager == null) return;

        int firstVisiblePos = layoutManager.findFirstVisibleItemPosition();
        if (firstVisiblePos == RecyclerView.NO_POSITION) {
            Log.w(TAG, "❌ 无法找到第一个可见项");
            return;
        }

        RecyclerView.ViewHolder holder = recyclerView.findViewHolderForLayoutPosition(firstVisiblePos);
        if (holder instanceof VideoViewHolder) {
            ((VideoViewHolder) holder).resume();
            Log.d("FragmentHomePage", "✅ 恢复播放: position=" + firstVisiblePos);
        } else {
            Log.w(TAG, "ViewHolder 不是 VideoViewHolder 类型: " + firstVisiblePos);
            // 可尝试延迟重试
            recyclerView.postDelayed(this::resumeVideoIfVisible, 50);
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        Log.d("FragmentHomePage", "✅ onResume: isResumed=" + isResumed() + ", isHidden=" + isHidden());        if (isResumed() && !isHidden()) {
            recyclerView.post(this::resumeVideoIfVisible);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            pauseAllVideos();
        } else {
            recyclerView.post(this::resumeVideoIfVisible);
        }
    }

    /**
     * 获取推荐视频列表（带排序）
     */
    private ArrayList<Video> getRecommendedVideos(User currentUser) {
        try {
            ArrayList<Video> allVideos = dbHelper.getAllVideos();

            // 为每个视频计算推荐分数
            Map<Video, Double> videoScores = new HashMap<>();
            for (Video video : allVideos) {
                double score = VideoRecommendationAlgorithm.calculateVideoScore(video, currentUser);
                videoScores.put(video, score);
            }

            // 按分数降序排序
            allVideos.sort((v1, v2) ->
                    Double.compare(videoScores.get(v2), videoScores.get(v1))
            );

            return allVideos;

        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    /**
     * 刷新视频数据（使用推荐算法）
     */
    public void refreshVideoData() {
        new Thread(() -> {
            try {
                if (shouldUseRecommendation) {
                    // 获取当前登录用户
                    User currentUser = getCurrentUser(); // 需要实现这个方法
                    ArrayList<Video> videos = getRecommendedVideos(currentUser);

                    if (getActivity() != null && !getActivity().isFinishing()) {
                        getActivity().runOnUiThread(() -> {
                            videoAdapter.setVideos(videos);

                            // 调试日志
                            Log.d("FragmentHomePage", "🎯 推荐视频列表（带排序），数量: " + videos.size());
                            for (int i = 0; i < Math.min(3, videos.size()); i++) {
                                Video video = videos.get(i);
                                Log.d("FragmentHomePage", "  推荐位 " + (i+1) + ": " + video.getTitle());
                            }
                        });
                    }
                    shouldUseRecommendation=false;
                }else{
                   ArrayList<Video> videos = dbHelper.getAllVideos();
                        // 在主线程更新UI
                    if (getActivity() != null && !getActivity().isFinishing()) {
                        getActivity().runOnUiThread(() -> {
                            videoAdapter.setVideos(videos);

                            // 输出调试信息
                            Log.d("FragmentHomePage", "📱 首页视频列表已刷新，数量: " + videos.size());
                            for (Video video : videos) {
                                Log.d("FragmentHomePage", "  视频: ID=" + video.getId() +
                                        ", 标题=" + video.getTitle() +
                                        ", 用户=" + video.getUserName());
                            }
                        });
                    }
                }

            } catch (Exception e) {
                Log.e("FragmentHomePage", "刷新推荐视频失败: " + e.getMessage(), e);
            }
        }).start();
    }

//    public void refreshVideoData() {
//        new Thread(() -> {
//            try {
//                ArrayList<Video> videos = dbHelper.getAllVideos();
//
//                // 在主线程更新UI
////                if (getActivity() != null) {
//                if (getActivity() != null && !getActivity().isFinishing()) {
//                    getActivity().runOnUiThread(() -> {
//                        videoAdapter.setVideos(videos);
//
//                        // 输出调试信息
//                        Log.d("FragmentHomePage", "📱 首页视频列表已刷新，数量: " + videos.size());
//                        for (Video video : videos) {
//                            Log.d("FragmentHomePage", "  视频: ID=" + video.getId() +
//                                    ", 标题=" + video.getTitle() +
//                                    ", 用户=" + video.getUserName());
//                        }
//                    });
//                }
//            } catch (Exception e) {
//                Log.e("FragmentHomePage", "刷新视频数据失败: " + e.getMessage(), e);
//            }
//        }).start();
//    }
    /**
     * 获取当前登录用户
     */
    private User getCurrentUser() {
        // 1. 从MainActivity获取数据库帮助类（避免重复创建）
        MainActivity mainActivity = (MainActivity) getActivity();
        if (mainActivity == null || mainActivity.getMySqLiteOpenHelper() == null) {
            Log.e(TAG, "获取当前用户失败：MainActivity或数据库实例为空");
            return null;
        }
        MySqLiteOpenHelper dbHelper = mainActivity.getMySqLiteOpenHelper();

        // 2. 调用ActivityLogin的静态方法，读取登录用户（路径和键名完全一致）
        User currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(requireContext(), dbHelper);
        if (currentUser == null || currentUser.getName() == null || currentUser.getId() == 0) {
            Log.e(TAG, "未获取到有效登录用户，User对象为空或ID/用户名为空");
            Log.d(TAG, "调试：currentUser=" + (currentUser != null ? currentUser.getName() : "null"));
            return null;
        }

        // 3. 校验用户是否存在于数据库（避免SP存储的用户已被删除）
        User dbUser = dbHelper.getUserByName(currentUser.getName().trim());
        if (dbUser == null) {
            Log.e(TAG, "SP中存储的用户不存在于数据库，用户名：" + currentUser.getName());
            // 清除无效的登录状态（调用ActivityLogin的SP路径）
            SharedPreferences sp = requireContext().getSharedPreferences(
                    ActivityLogin.SHARED_PREFRENCES_CURRENT_USER, Context.MODE_PRIVATE
            );
            sp.edit().clear().apply();
            return null;
        }

        Log.d(TAG, "获取到有效登录用户：用户名=" + dbUser.getName() + "，用户ID=" + dbUser.getId());
        return dbUser;
    }
}